<template>
  <div id="app" class="product-sample">
    <van-nav-bar left-arrow title="成品布样" @click-left="comeBack" left-text="返回">
      <template #right>
        <span @click="showAddDialogFn"><van-icon name="plus" size="20" /></span>
      </template>
    </van-nav-bar>
    <!-- 筛选 -->
    <van-search v-model="queryParam.keyLike" placeholder="请输入搜索关键词" @search="() => loadSampleDataFn(1)" />

    <!-- 滚动 -->
    <better-scroll class="body-scroll" :data="sampleData" :total-page="totalPage" :pulldown="true" :pullup="true" @pullup="loadNextPageFn" @pulldown="() => loadSampleDataFn(1)">
      <van-swipe-cell v-show="sampleData.length > 0" v-for="(row, rIndex) in sampleData" :key="row.id" style="padding-bottom: 0.5rem">
        <template>
          <div class="data-card">
            <div style="flex: 0 0 10vw; padding-right: 2vw;">
              <van-image width="100px" height="120px" fit="fill" :src="row.picView" @click="showPicPreViewFn(row)">
                <template v-slot:error>加载失败</template>
                <template v-slot:loading>
                  <van-loading type="spinner" size="20" />
                </template>
              </van-image>
            </div>
            <div style="flex: 1; flex-flow: column;">
              <div style="border-bottom: 1px solid #8191c5; color: #1677FF;justify-content: space-between">
                <span style="color: #8191c5;font-size: 1.1rem; ">{{ row.no }}</span>
                <span style="color: #8191c5;font-size: 1rem">{{ row.color }}</span>
              </div>
              <div style="justify-content: space-between">
                <span style="color: #e6a23c">品名: {{ row.name }}</span>
              </div>
              <div style="justify-content: space-between">
                <span style="color: #239a2a">克重: {{ row.miWeight }}g</span>
                <span style="color: #239a2a">门幅: {{ row.width }}cm</span>
              </div>
              <div style="justify-content: space-between">
                <span style="color: #4b4949">{{ doubleFlagEnum(row.doubleFlag) }}</span>
                <span style="color: #4b4949">{{ wayFlagEnum(row.wayFlag) }}</span>
                <span style="color: #4b4949">{{ jacquardFlagEnum(row.jacquardFlag) }}</span>
                <span style="color: #4b4949">{{ colorNumEnum(row.colorNum) }}</span>
              </div>
              <div style="justify-content: space-between">
                <span style="color: #e63c3c">{{ row.composition }}</span>
              </div>
              <div v-if="row.area != ''" style="justify-content: space-between">
                <span style="color: #2a2a2a">位置: {{ row.area }}</span>
              </div>
            </div>
          </div>
        </template>
        <template #right>
          <div style="display: flex; flex-flow: column; padding-right: 2vw;">
            <van-button square text="编辑" type="warning" @click="editSampleDataFn(row)" />
            <van-button square style="margin-top: 1vh;" text="删除" type="danger" @click="delSampleDataFn(row, rIndex)" />
            <van-button square style="margin-top: 1vh;" text="库存" type="info" @click="showStockFn(row)" />
          </div>
        </template>
      </van-swipe-cell>
      <van-empty  v-show="sampleData.length == 0" image="https://img01.yzcdn.cn/vant/custom-empty-image.png" description="暂无数据" ></van-empty>
    </better-scroll>

    <!-- 变更弹窗 -->
    <van-dialog v-model="showAddDialog" :title="addParam.id > 0 ? '编辑布样' : '新增布样'" :lock-scroll="false"  :show-confirm-button="false">
      <div style="width: 85vw; height: 60vh; overflow: auto">
        <van-form validate-first @submit="confirmChangeFn">
          <van-field label="货号" label-align="right" size="large" label-width="15vw" colon placeholder="请输入货号" v-model="addParam.no" :rules="[{ validator: validatorFn, message: '请输入货号' }]"></van-field>
          <van-field label="品名" label-align="right" size="large" label-width="15vw" colon placeholder="请输入品名" v-model="addParam.name" :rules="[{ validator: validatorFn, message: '请输入品名' }]"></van-field>
          <van-field label="颜色" label-align="right" size="large" label-width="15vw" colon placeholder="请输入颜色" v-model="addParam.color" :rules="[{ validator: validatorFn, message: '请输入颜色' }]" @input="showColorPopupFn"></van-field>
          <van-field label="米克重" label-align="right" size="large" label-width="15vw" colon placeholder="请输入米克重" v-model="addParam.miWeight" :rules="[{ validator: validatorFn, message: '请输入米克重' }]"></van-field>
          <van-field label="门幅" label-align="right" size="large" label-width="15vw" colon placeholder="请输入幅宽" v-model="addParam.width" :rules="[{ validator: validatorFn, message: '请输入幅宽' }]"></van-field>
          <van-field label="成份" label-align="right" size="large" label-width="15vw" colon placeholder="请输入成份" v-model="addParam.composition" :rules="[{ validator: validatorFn, message: '请输入成份' }]" readonly @click="showCompositionPopupFn"></van-field>
          <div v-if="compositions.length > 0" style="margin-left:10vw;">
            <van-field v-for="(composition, cIndex) in compositions" label-align="right" label-width="25vw" v-model="composition.percent" colon clearable @input="fillCompositionFn">
              <template #label>
                <span style="color: #1989fa;font-size: 0.9rem;line-height: 4vh;">{{ composition.type }}</span>
              </template>
              <template #button>
                <van-button native-type="button" size="small" type="danger" style="height: 4vh;" @click="delCompositionFn(cIndex)">删除</van-button>
              </template>
            </van-field>
          </div>
          <van-field label="单双面" label-align="right" size="large" label-width="15vw" colon>
            <template #input>
              <van-radio-group v-model="addParam.doubleFlag" direction="horizontal">
                <van-radio name="1" shape="square">单面</van-radio>
                <van-radio name="0" shape="square">双面</van-radio>
              </van-radio-group>
            </template>
          </van-field>
          <van-field label="方式" label-align="right" size="large" label-width="15vw" colon>
            <template #input>
              <van-radio-group v-model="addParam.wayFlag" direction="horizontal">
                <van-radio name="1" shape="square">针织</van-radio>
                <van-radio name="2" shape="square">梭织</van-radio>
              </van-radio-group>
            </template>
          </van-field>
          <van-field label="组织" label-align="right" size="large" label-width="15vw" colon>
            <template #input>
              <van-radio-group v-model="addParam.jacquardFlag" direction="horizontal">
                <van-radio name="0" shape="square">一般</van-radio>
                <van-radio name="1" shape="square">提花</van-radio>
              </van-radio-group>
            </template>
          </van-field>
          <van-field label="花纹" label-align="right" size="large" label-width="15vw" colon>
            <template #input>
              <van-radio-group v-model="addParam.colorNum" direction="horizontal">
                <van-radio style="margin-bottom: 1vh;" name="1" shape="square">素色</van-radio>
                <van-radio style="margin-bottom: 1vh;" name="2" shape="square">混色</van-radio>
                <van-radio style="margin-bottom: 1vh;" name="3" shape="square">格子</van-radio>
                <van-radio style="margin-bottom: 1vh;" name="4" shape="square">条纹</van-radio>
                <van-radio style="margin-bottom: 1vh;" name="5" shape="square">其他</van-radio>
              </van-radio-group>
            </template>
          </van-field>
          <van-field label="位置" label-align="right" size="large" label-width="15vw" colon placeholder="请输入位置" v-model="addParam.area"></van-field>
          <van-field label="图片" label-align="right" size="large" label-width="15vw" colon>
            <template #input>
              <van-uploader style="margin: 10px" preview-size="10rem" v-model="uploadFileList" :max-count="5"></van-uploader>
            </template>
          </van-field>
          <div style="margin: 16px;display: flex;justify-content: center;width: 90%;">
            <van-button block type="danger" native-type="button" @click="showAddDialog = false">取消</van-button>
            <van-button style="margin-left: 10vw;" block type="info" native-type="submit">提交</van-button>
          </div>
        </van-form>
      </div>
    </van-dialog>

    <!-- 颜色选择 -->
    <van-popup v-model="showColorPopup" position="bottom" get-container="body">
      <van-picker show-toolbar value-key="name" :columns="colorColumn" @confirm="selectColorFn" @cancel="showColorPopup = false"></van-picker>
    </van-popup>

    <!-- 类型选择 -->
    <van-popup v-model="showTypePopup" position="bottom" get-container="body">
      <van-picker show-toolbar value-key="name" :columns="typeColumn" @confirm="selectTypeFn" @cancel="showTypePopup = false"></van-picker>
    </van-popup>

    <!-- 图片预览 -->
    <van-image-preview v-model="showProductPicPreViewFlag" :showIndex="false" :closeable="true" :images="productPicPreview">
    </van-image-preview>
  </div>
</template>

<script>
import {comeBack, getFloat, openWin} from "@/utils";
import {addProductSample, delProductSample, editProductSample, filterSampleColor, loadSampleData} from "@/api/product";
import {
  colorNumEnum,
  doubleFlagEnum,
  jacquardFlagEnum,
  SPLIT_COMMA,
  SPLIT_HX,
  SPLIT_NO,
  SPLIT_PERCENT,
  wayFlagEnum
} from "@/api/enum";
import {filterMaterialField} from "@/api/material";
import {getUploadKey} from "@/api/public";
import {exportBaseUrl} from "@/utils/request";
import {picUpload} from "@/api/common";


export default {
  name: "productSample",
  data() {
    return {
      /* 查询相关 */
      queryParam: {
        keyLike: "",
        pageNum: 1,
        pageSize: 6,
      },
      queryTimer: null,

      /* 列表相关 */
      sampleData: [],
      totalPage: 0,

      /* 操作相关 */
      picType: "CPBY",
      showAddDialog: false,
      addParam: {
        id: 0,
        no: "",
        name: "",
        color: "",
        miWeight: "",
        width: "",
        composition: "",
        pic: "",
        doubleFlag: "1",
        wayFlag: "1",
        jacquardFlag: "0",
        colorNum: "1",
        area: "",
      },
      compositions: [],    //成份数组
      uploadFileList: [],
      showColorPopup: false,
      colorColumn: [],
      showTypePopup: false,
      typeColumn: [],

      /* 图片预览相关 */
      showProductPicPreViewFlag: false,
      productPicPreview: [],
    };
  },
  mounted() {
    const that = this;
    if (process.env.NODE_ENV === "production") {
      that.$nextTick(() => {
        that.initFn(that);
      });
    } else {
      window.apiready = function () {
        that.initFn(that);
      };
    }

    // that.initFn(that);   //dev fixme
  },
  methods: {
    comeBack,
    doubleFlagEnum,
    wayFlagEnum,
    jacquardFlagEnum,
    colorNumEnum,

    /* 初始化 */
    initFn() {
      const that = this;
      filterMaterialField({
        type: "type",
        key: ""
      }, data => {
        data.forEach(type => {
          that.typeColumn.push(type);
        });
      });

      that.loadSampleDataFn(1);
    },

    /* 重置 */
    resetProps() {
      const that = this;
      that.addParam.id = 0;   //重置ID
      that.queryParam.keyLike = "";
      that.queryParam.pageNum = 1;
      that.sampleData.splice(0, that.sampleData.length);    //三方组件有问题 先用这个
      that.uploadFileList.splice(0, that.uploadFileList.length);    //上传文件置空
      that.productPicPreview.splice(0, that.productPicPreview.length);    //成品图置空
    },

    /* 显示颜色弹窗 */
    showColorPopupFn() {
      const that = this;
      clearTimeout(that.queryTimer);
      that.queryTimer = setTimeout(() => {
        that.colorColumn.splice(0, that.colorColumn.length);
        filterSampleColor({color: that.addParam.color}, data => {
          if(data.length == 0) {
            that.colorColumn.push(that.addParam.color);
          } else {
            data.forEach(color => {
              that.colorColumn.push(color);
            });
          }
          that.showColorPopup = true;
        });
      }, 1500);
    },
    /* 选择颜色 */
    selectColorFn(color) {
      const that = this;
      if(color.split(SPLIT_NO).length < 2) {
        that.$toast.fail("颜色格式:\n 0000#颜色名")
        return;
      }
      that.addParam.color = color;
      that.showColorPopup = false;
    },

    /* 显示成份弹窗 */
    showCompositionPopupFn() {
      const that = this;
      that.showTypePopup = true;
    },
    /* 选择类型 */
    selectTypeFn(type) {
      const that = this;
      that.compositions.push({
        type: type,
        percent: "",
      });
      that.showTypePopup = false;
    },
    /* 删除成份 */
    delCompositionFn(cIndex) {
      const that = this;
      that.compositions.splice(cIndex, 1);
      if(that.compositions.length > 0) {
        that.fillCompositionFn();
      } else {
        that.addParam.composition = "";
      }
    },
    /* 更改输入框 */
    fillCompositionFn() {
      const that = this;
      that.addParam.composition = that.compositions.filter(c => c.percent != "").map(c => c.percent + "%" + c.type.split(SPLIT_HX)[1]).join(SPLIT_COMMA);
    },

    /* 字段校验 */
    validatorFn(val, rule) {
      const that = this;
      let result = val != "";
      if(!result) {
        that.$toast.fail(rule.message);
      }
      return result;
    },

    /* 确认更改 */
    confirmChangeFn() {
      const that = this;
      //校验参数
      if(that.uploadFileList.length == 0) {
        that.$toast.fail("请上传图片");
        return false;
      }
      let compositionPercent = 0;
      if(that.compositions.length == 1) {
        compositionPercent = that.compositions[0].percent;
      } else {
        compositionPercent = getFloat(that.compositions.map(c => Number(c.percent)).reduce((a,b) => Number(a) + Number(b)), 0);
      }
      if(compositionPercent != 100) {
        that.$toast.fail("成份含量不是100%");
        return false;
      }

      //编辑时候图片无更新
      if(that.addParam.id > 0 && that.uploadFileList.every(uploadFile => uploadFile.name)) {    //图片无更新或者删除
        that.addParam.pic = that.uploadFileList.map(uploadFile => uploadFile.name).join(SPLIT_COMMA);
        editProductSample(that.addParam, that.afterChangeFn);
        return;
      }

      //上传
      picUpload(that, that.uploadFileList, res => {
        if(that.addParam.id > 0) {
          let tmpArray = that.uploadFileList.filter(uploadFile => uploadFile.name).map(uploadFile => uploadFile.name);
          tmpArray.push(res.data);
          that.addParam.pic = tmpArray.join(SPLIT_COMMA);
          editProductSample(that.addParam, that.afterChangeFn);
        } else {
          //保存文件名
          that.addParam.pic = res.data;
          addProductSample(that.addParam, that.afterChangeFn);
        }
      });

      //上传
      /*getUploadKey({
        type: that.picType
      }, tokenRes => {
        let form = new FormData();
        that.uploadFileList.filter(uploadFile => uploadFile.file).forEach(uploadFile => {
          form.append("files", uploadFile.file);
          uploadFile.status = "uploading";
          uploadFile.message  = "上传中...";
        });
        that.$toast.loading({
          message: '加载中...',
          forbidClick: true,
          duration: 60000,
          loadingType: 'spinner'
        });
        let oReqCos = new XMLHttpRequest();
        oReqCos.open('POST', exportBaseUrl("res") + '/file_upload/upload_pic');
        oReqCos.setRequestHeader('x-yd-access-token', tokenRes.accessToken);
        oReqCos.onload = function () {
          if (oReqCos.status === 200) {
            let res = JSON.parse(oReqCos.response)
            if (res.code === 2000) {
              if(that.addParam.id > 0) {
                let tmpArray = that.uploadFileList.filter(uploadFile => uploadFile.name).map(uploadFile => uploadFile.name);
                tmpArray.push(res.data);
                that.addParam.pic = tmpArray.join(SPLIT_COMMA);
                editProductSample(that.addParam, that.afterChangeFn);
              } else {
                //保存文件名
                that.addParam.pic = res.data;
                addProductSample(that.addParam, that.afterChangeFn);
              }
            } else {
              that.uploadFileList.forEach(uploadFile => {
                uploadFile.status = "done";
              });
              that.$toast.fail(res.msg);
            }
          } else {
            that.$toast.fail("未知原因");
          }
        }
        oReqCos.send(form);
      });*/
    },
    afterChangeFn(res) {
      const that = this;
      if(res.code || res.code == 0) {
        that.uploadFileList.forEach(uploadFile => {
          uploadFile.status = "done";
        });
        that.$toast.fail(res.msg);
      } else {
        that.$toast.success("增加成功");
        that.showAddDialog = false;
        that.loadSampleDataFn(1);
        that.resetProps();
      }
    },

    /* 加载布样数据 */
    loadSampleDataFn(pageNum) {
      let that = this;
      if(pageNum == 1) {
        that.sampleData.splice(0, that.sampleData.length);
        that.queryParam.pageNum = pageNum;
      }
      loadSampleData(that.queryParam, data => {
        that.totalPage = data.totalPage;
        data.list.forEach(row => {
          row.picView = "";
          getUploadKey({
            type: that.picType
          }, tokenRes => {
            row.picView = exportBaseUrl("res") + "/res_thumb/" + row.pic.split(SPLIT_COMMA)[0] + '?accessToken=' + tokenRes.accessToken;
          });
          that.sampleData.push(row);
        });
      });
    },

    /* 加载下一页 */
    loadNextPageFn() {
      let that = this;
      that.queryParam.pageNum++;
      that.loadSampleDataFn();
    },

    /* 查看图片 */
    showPicPreViewFn(row) {
      const that = this;
      that.productPicPreview.splice(0, that.productPicPreview.length);
      row.pic.split(SPLIT_COMMA).forEach(pic => {
        getUploadKey({
          type: that.picType
        }, tokenRes => {
          that.productPicPreview.push(exportBaseUrl("res") + "/res/" + pic + '?accessToken=' + tokenRes.accessToken);
        });
      });
      that.showProductPicPreViewFlag = true;
    },

    /* 删除样品数据 */
    delSampleDataFn(row, rIndex) {
      const that = this;
      delProductSample({sampleId: row.id}, () => {
        that.sampleData.splice(rIndex, 1);
      });
    },

    /* 显示增加窗口 */
    showAddDialogFn() {
      const that = this;
      that.addParam.id = 0;
      that.showAddDialog = true;
      that.uploadFileList.splice(0, that.uploadFileList.length);
    },

    /* 编辑样品数据 */
    editSampleDataFn(row) {
      const that = this;
      that.addParam.id = row.id;
      Object.keys(row).forEach(key => {
        if(key != "id") {
          that.addParam[key] = String(row[key]);
        }
      });
      //处理成份
      that.compositions.splice(0, that.compositions.length);
      that.addParam.composition.split(SPLIT_COMMA).forEach(composition => {
        let tmp = composition.split(SPLIT_PERCENT);   //0-percent; 1-type
        let type = that.typeColumn.find(column => column.endsWith(tmp[1]));
        that.compositions.push({
          type: type,
          percent: tmp[0]
        })
      });

      that.showAddDialog = true;
      that.uploadFileList.splice(0, that.uploadFileList.length);
      that.addParam.pic.split(SPLIT_COMMA).forEach(pic => {
        getUploadKey({
          type: that.picType
        }, tokenRes => {
          that.uploadFileList.push({
            url: exportBaseUrl("res") + "/res/" + pic + '?accessToken=' + tokenRes.accessToken,
            name: pic
          });
        });
      })
    },

    /* 显示库存 */
    showStockFn(row) {
      openWin("cloth-store-view", {keyLike: row.no});
    }
  }
}
</script>

<style lang="scss" scoped>
.product-sample {
  height: 100%;
  ::v-deep .van-search {
    z-index: 1;
  }
  .body-scroll {
    height: 79vh;
    .van-swipe-cell__right {
      display: flex;
      flex-flow: column;
    }
    .data-card {
      width: 96vw;
      padding: 0.8rem;
      margin-left: 2vw;
      background-color: white;
      margin-top: 0.5rem;
      box-shadow: 0.3rem 0.5rem 0.3rem #888888;
      display: flex;
      div {
        display: flex;
        padding: 0.3rem 0rem;
        span {
          line-height: 1rem;
        }
      }
    }
  }
}
</style>